﻿using System;
using System.Collections.Generic;
using System.Text; 
using System.Web;
using System.Xml;
using System.IO;
using System.Net;
using System.Data;
using System.Data.SQLite;
using System.Text.RegularExpressions;

namespace NetOpen_System.Component
{
    public sealed class WebsiteVisitHttpModule : IHttpModule
    {
        #region IHttpModule 成员

        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest);
        }


        #endregion
        
        private const string _regexSEQuery = @"(?<=(\&|\?|^)({0})\=).*?(?=\&|$)";

        private string GetLengthString(string stringToSub, int length)  
        {   
            Regex regex = new Regex("[\u4e00-\u9fa5]+", RegexOptions.Compiled);   
            char[] stringChar = stringToSub.ToCharArray();   
            StringBuilder sb = new StringBuilder();   
            int nLength = 0;   
            //C#截取字符串 
            for(int i = 0; i < stringChar.Length; i++)   
            {   
                if (regex.IsMatch((stringChar[i]).ToString()))   
                {   nLength += 2;   }   
                else   
                {  
                    nLength = nLength + 1;   
                }    
                if (nLength <= length)   
                {   
                    sb.Append(stringChar[i]);   
                }   
                else   
                {   
                    break;   
                }  
            }
                //C#截取字符串  
                if(sb.ToString() != stringToSub)   
                {  

                }  
                return sb.ToString();  
        }

        /// <summary>
        /// 查找关键字
        /// </summary>
        /// <param name="input">源字符串</param>
        /// <param name="querykey">>多个QueryKey按优先顺序用'|'分隔</param>
        /// <param name="options"</param>
        /// <returns></returns>
        private string RegexMatch(string input, string querykey, RegexOptions options)
        {
            return Regex.Match(input, string.Format(_regexSEQuery, querykey), options).Value.Trim();
        }

        /// <summary>
        /// 统计源字符串中包含多少目标字符串
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <param name="dest">目标字符串</param>
        /// <returns>出现次数</returns>
        private int SubString(string source, string dest)
        {
            MatchCollection mc = Regex.Matches(source, dest);

            return mc.Count;
        }

        /// <summary>
        /// 获取目标字符串在源字符串中指定出现次数的索引
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <param name="dest">目标字符串</param>
        /// <param name="ordinalNumber">出现序数</param>
        /// <returns>出现位置索引</returns>
        private int SubString(string source, string dest, int ordinalNumber)
        {
            MatchCollection mc = Regex.Matches(source, dest);

            if (mc.Count < ordinalNumber)
            {
                return -1;

            }
            else
            {
                return mc[ordinalNumber - 1].Index;
            }
        }
        
        /// <summary>
        /// 获取源字符串中在指定序数的目标字符串之后的字符串
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <param name="dest">目标字符串</param>
        /// <param name="ordinalNumber">出现序数</param>
        /// <param name="returnStringlength">返回字符串的长度</param>
        /// <returns>获取的字符串，不成功为null</returns>
        private string SubString(string source, string dest, int ordinalNumber, int returnStringlength)
        {
            int pos = SubString(source, dest, ordinalNumber);

            if (pos != -1)
            {
                return source.Substring(pos + dest.Length, returnStringlength);

            }
            else
            {
                return null;

            }

        }


        void context_BeginRequest(object sender, EventArgs e)
        {
            try
            {
                HttpApplication objApp = (HttpApplication)sender;
                string ls_datasource = string.Empty;
                string ls_datesource = string.Empty;
                string ls_website = string.Empty;
                string ls_decodeurl = string.Empty;
                string ls_textdecoding = string.Empty;
                string ls_webcookiesname = string.Empty;
                string ls_webcookiesvalue = string.Empty;
                string ls_webcookiesexpires = string.Empty;

                string ls_ismappath = WebsiteVisitConfiguration.GetConfig().IsMapPath;
                ls_website = WebsiteVisitConfiguration.GetConfig().Website;
                ls_decodeurl = WebsiteVisitConfiguration.GetConfig().DecodeUrl;
                ls_textdecoding = WebsiteVisitConfiguration.GetConfig().TextDecoding;
                ls_webcookiesname = WebsiteVisitConfiguration.GetConfig().WebCookiesName;
                ls_webcookiesexpires = WebsiteVisitConfiguration.GetConfig().WebCookiesExpires;

                if (ls_website.Length > 100)
                {
                    ls_website = ls_website.Substring(0, 100);
                }

                if (WebsiteVisitConfiguration.GetConfig().DateSource.ToLower() == "month")
                {
                    ls_datesource = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString();
                }
                else if (WebsiteVisitConfiguration.GetConfig().DateSource.ToLower() == "year")
                {
                    ls_datesource = DateTime.Now.Year.ToString();
                }
                else if (WebsiteVisitConfiguration.GetConfig().DateSource.ToLower() == "day")
                {
                    ls_datesource = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString();
                }

                if (string.IsNullOrEmpty(ls_datesource))
                {
                    if (ls_ismappath.ToLower() == "yes")
                    {
                        ls_datasource = objApp.Server.MapPath(WebsiteVisitConfiguration.GetConfig().DataSource.Trim());
                    }
                    else
                    {
                        ls_datasource = WebsiteVisitConfiguration.GetConfig().DataSource.Trim();
                    }
                }
                else
                {
                    if (ls_ismappath.ToLower() == "yes")
                    {
                        ls_datasource = objApp.Server.MapPath(WebsiteVisitConfiguration.GetConfig().DataSource.Trim() + ls_datesource.Trim() + ".db");
                    }
                    else
                    {
                        ls_datasource = WebsiteVisitConfiguration.GetConfig().DataSource.Trim() + ls_datesource.Trim() + ".db";
                    }
                }

               
                if (!File.Exists(ls_datasource))
                {
                     SQLiteConnection.CreateFile(ls_datasource);
                     SQLiteConnectionStringBuilder builder = new SQLiteConnectionStringBuilder();
                     builder.DataSource = ls_datasource;
                     builder.Password = WebsiteVisitConfiguration.GetConfig().PassWord;
                     using (SQLiteConnection cnn = new SQLiteConnection(builder.ConnectionString))
                     {
                         //打开数据库
                         cnn.Open();
                         using (SQLiteTransaction dbsqlTrans = cnn.BeginTransaction()) //使用事务
                         {
                             using (SQLiteCommand sqlcmd = new SQLiteCommand())
                             {
                                 sqlcmd.Connection = cnn;
                                 StringBuilder sbsql = new StringBuilder();
                                 sbsql.Append("CREATE TABLE [UserVisitLog] (");
                                 sbsql.Append("[Id] integer PRIMARY KEY AUTOINCREMENT NOT NULL COLLATE NOCASE,");
                                 sbsql.Append("[UserHostAddress] varchar(20) COLLATE NOCASE,");
                                 sbsql.Append("[UserHostName] varchar(20) COLLATE NOCASE,");
                                 sbsql.Append("[UrlAbsoluteUri] varchar(1600) COLLATE NOCASE,");
                                 sbsql.Append("[PhysicalPath] varchar(500) COLLATE NOCASE,");
                                 sbsql.Append("[UserAgent] varchar(1000) COLLATE NOCASE,");
                                 sbsql.Append("[HttpMethod] varchar(4) COLLATE NOCASE,");
                                 sbsql.Append("[UserLanguages] varchar(20) COLLATE NOCASE,");
                                 sbsql.Append("[UrlHost] varchar(100) COLLATE NOCASE,");
                                 sbsql.Append("[UrlPort] varchar(10) COLLATE NOCASE,");
                                 sbsql.Append("[TotalBytes] integer COLLATE NOCASE,");
                                 sbsql.Append("[ContentLength] integer COLLATE NOCASE,");
                                 sbsql.Append("[IsLocal] varchar(5),");
                                 sbsql.Append("[BrowserType] varchar(30) COLLATE NOCASE,");
                                 sbsql.Append("[BrowserVersion] varchar(20) COLLATE NOCASE,");
                                 sbsql.Append("[BrowserPlatform] varchar(20) COLLATE NOCASE,");
                                 sbsql.Append("[BrowserBeta] varchar(5) COLLATE NOCASE,");
                                 sbsql.Append("[BrowserActiveXControls] varchar(5) COLLATE NOCASE,");
                                 sbsql.Append("[BrowserCookies] varchar(5) COLLATE NOCASE,");
                                 sbsql.Append("[BrowserCrawler] varchar(5) COLLATE NOCASE,");
                                 sbsql.Append("[BrowserJavaScript] varchar(5) COLLATE NOCASE,");
                                 sbsql.Append("[BrowserSupportsXmlHttp] varchar(5) COLLATE NOCASE,");
                                 sbsql.Append("[BrowserInputType] varchar(30) COLLATE NOCASE,");
                                 sbsql.Append("[BrowserScreenPixelsWidth] integer COLLATE NOCASE,");
                                 sbsql.Append("[BrowserScreenPixelsHeight] integer COLLATE NOCASE,");
                                 sbsql.Append("[UrlReferrerAbsoluteUri] varchar(1600) COLLATE NOCASE,");
                                 sbsql.Append("[UrlReferrerAbsoluteUriDecode] varchar(1600) COLLATE NOCASE,");
                                 sbsql.Append("[UrlReferrerHostName] varchar(100) COLLATE NOCASE,");
                                 sbsql.Append("[CanCombineFormsInDeck] varchar(5) COLLATE NOCASE,");
                                 sbsql.Append("[IsMobileDevice] varchar(5) COLLATE NOCASE,");
                                 sbsql.Append("[MobileDeviceManufacturer] varchar(30) COLLATE NOCASE,");
                                 sbsql.Append("[MobileDeviceModel] varchar(30) COLLATE NOCASE,");
                                 sbsql.Append("[NumberOfSoftkeys] integer COLLATE NOCASE,");
                                 sbsql.Append("[ContentEncoding] varchar(10) COLLATE NOCASE,");
                                 sbsql.Append("[ScreenBitDepth] integer COLLATE NOCASE,");
                                 sbsql.Append("[Website] varchar(100) COLLATE NOCASE,");
                                 sbsql.Append("[WebCookies] varchar(80) COLLATE NOCASE,");
                                 sbsql.Append("[VisitTime] varchar(20) COLLATE NOCASE);");
                                 sqlcmd.CommandText = sbsql.ToString();
                                 sqlcmd.ExecuteNonQuery();
                                 dbsqlTrans.Commit();     //提交事务执行
                             }
                         }
                     }

                }

                if (WebsiteVisitConfiguration.GetConfig().ExcludeUrl.Trim().Length > 0)
                {
                    if (objApp.Request.Url.AbsoluteUri.Trim() == WebsiteVisitConfiguration.GetConfig().ExcludeUrl.Trim())
                    {
                        return;
                    }
                }

                using (SQLiteConnection cn = new SQLiteConnection("Data Source=" + ls_datasource + ";Password=" + WebsiteVisitConfiguration.GetConfig().PassWord))
                {
                    //打开数据库
                    cn.Open();
                    using (SQLiteTransaction dbTrans = cn.BeginTransaction()) //使用事务
                    {

                        using (SQLiteCommand cmd = new SQLiteCommand())
                        {
                            cmd.Connection = cn;
                            StringBuilder sb = new StringBuilder();
                            sb.Append("Insert Into [UserVisitLog](UserHostAddress,UserHostName,UrlAbsoluteUri,PhysicalPath");
                            sb.Append(",UserAgent");
                            sb.Append(",HttpMethod");
                            sb.Append(",UserLanguages");
                            sb.Append(",UrlHost");
                            sb.Append(",UrlPort");
                            sb.Append(",TotalBytes");
                            sb.Append(",ContentLength");
                            sb.Append(",IsLocal");
                            sb.Append(",BrowserType");
                            sb.Append(",BrowserVersion");
                            sb.Append(",BrowserPlatform");
                            sb.Append(",BrowserBeta");
                            sb.Append(",BrowserActiveXControls");
                            sb.Append(",BrowserCookies");
                            sb.Append(",BrowserCrawler");
                            sb.Append(",BrowserJavaScript");
                            sb.Append(",BrowserSupportsXmlHttp");
                            sb.Append(",BrowserInputType");
                            sb.Append(",BrowserScreenPixelsWidth");
                            sb.Append(",BrowserScreenPixelsHeight");
                            sb.Append(",UrlReferrerAbsoluteUri");
                            sb.Append(",UrlReferrerAbsoluteUriDecode");
                            sb.Append(",UrlReferrerHostName");
                            sb.Append(",CanCombineFormsInDeck");
                            sb.Append(",IsMobileDevice");
                            sb.Append(",MobileDeviceManufacturer");
                            sb.Append(",MobileDeviceModel");
                            sb.Append(",NumberOfSoftkeys");
                            sb.Append(",ContentEncoding");
                            sb.Append(",ScreenBitDepth");
                            sb.Append(",Website");
                            sb.Append(",WebCookies");
                            sb.Append(",VisitTime");
                            sb.Append(") Values(");
                            //string ls_userhostaddress = objApp.Request.UserHostAddress;
                            string ls_userhostaddress = string.Empty;
                            if (objApp.Request.ServerVariables["HTTP_X_REAL_IP"] != null)
                            {
                                ls_userhostaddress = objApp.Request.ServerVariables["HTTP_X_REAL_IP"].ToString();
                            }
                            else if (objApp.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
                            {
                                ls_userhostaddress = objApp.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
                            }
                            else if (objApp.Request.ServerVariables["HTTP_VIA"] != null)
                            {
                                ls_userhostaddress = objApp.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
                            }
                            else
                            {
                                ls_userhostaddress = objApp.Request.ServerVariables["REMOTE_ADDR"].ToString();
                            }   
                            if (ls_userhostaddress.Length > 20)
                            {
                                ls_userhostaddress = ls_userhostaddress.Substring(0, 20);
                            }
                            sb.Append("'" + ls_userhostaddress + "',");
                            string ls_userhostname = objApp.Request.UserHostName;
                            if (ls_userhostname.Length > 20)
                            {
                                ls_userhostname = ls_userhostname.Substring(0, 20);
                            }
                            sb.Append("'" + ls_userhostname + "',");
                            string ls_absoluteuri = objApp.Request.Url.AbsoluteUri;

                            if (ls_decodeurl.Trim().Length > 0 )
                            {
                                string s = ls_decodeurl;

                                string[] sArray = s.Split(new char[]{';'});
                                if (sArray.Length > 1)
                                {
                                    foreach (string t in sArray)
                                    {
                                        if (ls_absoluteuri.Contains(t))
                                        {
                                            ls_absoluteuri = System.Web.HttpUtility.UrlDecode(ls_absoluteuri, System.Text.Encoding.GetEncoding(ls_textdecoding));
                                            break;
                                        }
                                    }
                                }
                                else
                                {
                                    if (ls_absoluteuri.Contains(ls_decodeurl))
                                    {
                                        ls_absoluteuri = System.Web.HttpUtility.UrlDecode(ls_absoluteuri, System.Text.Encoding.GetEncoding(ls_textdecoding));
                                    }
                                }
                            }

                            if (ls_absoluteuri.Length > 1600)
                            {
                                ls_absoluteuri = ls_absoluteuri.Substring(0, 1600);
                            }
                          
                            sb.Append("'" + ls_absoluteuri + "',");
                            string ls_physicalpath = objApp.Request.PhysicalPath;
                            if (ls_physicalpath.Length > 500)
                            {
                                ls_physicalpath = ls_physicalpath.Substring(0, 500);
                            }
                            sb.Append("'" + ls_physicalpath + "'");
                            string ls_useragent = objApp.Request.UserAgent;
                            if (ls_useragent.Length > 1000)
                            {
                                ls_useragent = ls_useragent.Substring(0, 1000);
                            }
                            sb.Append(",'" + ls_useragent + "'");
                            string ls_httpmethod = objApp.Request.HttpMethod;
                            if (ls_httpmethod.Length > 4)
                            {
                                ls_httpmethod = ls_httpmethod.Substring(0, 4);
                            }
                            sb.Append(",'" + ls_httpmethod + "'");
                            string ls_userlanguages = objApp.Request.UserLanguages[0];
                            if (ls_userlanguages.Length > 20)
                            {
                                ls_userlanguages = ls_userlanguages.Substring(0, 20);
                            }
                            sb.Append(",'" + ls_userlanguages + "'");
                            string ls_urlhost = objApp.Request.Url.Host;
                            if (ls_urlhost.Length > 100)
                            {
                                ls_urlhost = ls_urlhost.Substring(0, 100);
                            }
                            sb.Append(",'" + ls_urlhost + "'");
                            string ls_urlport = objApp.Request.Url.Port.ToString();
                            if (ls_urlport.Length > 10)
                            {
                                ls_urlport = ls_urlport.Substring(0, 10);
                            }
                            sb.Append(",'" + ls_urlport + "'");
                            sb.Append("," + objApp.Request.TotalBytes);
                            sb.Append("," + objApp.Request.ContentLength);
                            string ls_islocal = objApp.Request.IsLocal.ToString();
                            if (ls_islocal.Length > 5)
                            {
                                ls_islocal = ls_islocal.Substring(0, 5);
                            }
                            sb.Append(",'" + ls_islocal + "'");
                            string ls_browsertype = objApp.Request.Browser.Type;
                            if (ls_browsertype.Length > 30)
                            {
                                ls_browsertype = ls_browsertype.Substring(0, 30);
                            }
                            sb.Append(",'" + ls_browsertype + "'");
                            string ls_browserversion = objApp.Request.Browser.Version;
                            if (ls_browserversion.Length > 20)
                            {
                                ls_browserversion = ls_browserversion.Substring(0, 20);
                            }
                            sb.Append(",'" + ls_browserversion + "'");
                            string ls_browserplatform = objApp.Request.Browser.Platform;
                            if (ls_browserplatform.Length > 20)
                            {
                                ls_browserplatform = ls_browserplatform.Substring(0, 20);
                            }
                            sb.Append(",'" + ls_browserplatform+ "'");
                            string ls_browserbeta = objApp.Request.Browser.Beta.ToString();
                            if (ls_browserbeta.Length > 5)
                            {
                                ls_browserbeta = ls_browserbeta.Substring(0, 5);
                            }
                            sb.Append(",'" + ls_browserbeta + "'");
                            string ls_browseractivexcontrols = objApp.Request.Browser.ActiveXControls.ToString();
                            if (ls_browseractivexcontrols.Length > 5)
                            {
                                ls_browseractivexcontrols = ls_browseractivexcontrols.Substring(0, 5);
                            }
                            sb.Append(",'" + ls_browseractivexcontrols + "'");
                            string ls_browsercookies = objApp.Request.Browser.Cookies.ToString();
                            if (ls_browsercookies.Length > 5)
                            {
                                ls_browsercookies = ls_browsercookies.Substring(0, 5);
                            }
                            sb.Append(",'" + ls_browsercookies + "'");
                            string ls_browsercrawler = objApp.Request.Browser.Crawler.ToString();
                            if (ls_browsercrawler.Length > 5)
                            {
                                ls_browsercrawler = ls_browsercrawler.Substring(0, 5);
                            }
                            sb.Append(",'" + ls_browsercrawler + "'");
                            string ls_browserjavascript = objApp.Request.Browser.EcmaScriptVersion.Major.ToString();
                            if (ls_browserjavascript.Length > 5)
                            {
                                ls_browserjavascript = ls_browserjavascript.Substring(0, 5);
                            }
                            sb.Append(",'" + ls_browserjavascript+ "'");
                            string ls_browsersupportsxmlhttp = objApp.Request.Browser.SupportsXmlHttp.ToString();
                            if (ls_browsersupportsxmlhttp.Length > 5)
                            {
                                ls_browsersupportsxmlhttp = ls_browsersupportsxmlhttp.Substring(0, 5);
                            }
                            sb.Append(",'" + ls_browsersupportsxmlhttp + "'");
                            string ls_browserinputype = objApp.Request.Browser.InputType;
                            if (ls_browserinputype.Length > 30)
                            {
                                ls_browserinputype = ls_browserinputype.Substring(0, 30);
                            }
                            sb.Append(",'" + ls_browserinputype + "'");
                            sb.Append("," + objApp.Request.Browser.ScreenPixelsWidth);
                            sb.Append("," + objApp.Request.Browser.ScreenPixelsHeight);
                            string ls_urlrefer = string.Empty;
                            string ls_urlreferdecode = string.Empty;
                            string ls_urlreferhostname = string.Empty;
                            string ls_urlreferdecode2 = string.Empty;

                            if (objApp.Request.UrlReferrer != null)
                            {
                                ls_urlrefer = objApp.Request.UrlReferrer.AbsoluteUri;
                                ls_urlreferhostname = objApp.Request.UrlReferrer.Host.ToString();

                                //if (ls_urlrefer.ToLower().Contains(@"ie=gb2312"))
                                //{
                                //    ls_urlreferdecode = System.Web.HttpUtility.UrlDecode(ls_urlrefer, System.Text.Encoding.GetEncoding("gb2312"));
                                //}
                                //else if (ls_urlrefer.ToLower().Contains("utf-8") || ls_urlrefer.ToLower().Contains("utf8"))
                                //{
                                //    ls_urlreferdecode = System.Web.HttpUtility.UrlDecode(ls_urlrefer, System.Text.Encoding.GetEncoding("utf-8"));
                                //}
                                //else
                                //{
                                //    string ls_q = RegexMatch(ls_urlrefer, "wd|word|q|p|search|k|w|query|kw", RegexOptions.IgnoreCase);
                                //    int li_count = SubString(ls_q, @"%");

                                //    if (li_count > 0)
                                //    {
                                //        if (li_count % 3 == 0&& li_count %2 != 0) //utf-8
                                //        {
                                //            ls_urlreferdecode = System.Web.HttpUtility.UrlDecode(ls_urlrefer, System.Text.Encoding.GetEncoding("utf-8"));
                                //        }
                                //        else 
                                //        {
                                //            if (ls_urlrefer.ToLower().Contains("google") || ls_urlreferhostname.Contains("bing") || ls_urlreferhostname.Contains("yahoo") || ls_urlreferhostname.Contains("dmoz") || ls_urlreferhostname.Contains(@"people258.com/Search/SearchResult.aspx"))
                                //            {
                                //                ls_urlreferdecode = System.Web.HttpUtility.UrlDecode(ls_urlrefer, System.Text.Encoding.GetEncoding("utf-8"));
                                //            }
                                //            else if (ls_urlrefer.ToLower().Contains("baidu") || ls_urlreferhostname.ToLower().Contains("soso") || ls_urlreferhostname.ToLower().Contains("youdao") || ls_urlreferhostname.ToLower().Contains("sogou") || ls_urlreferhostname.ToLower().Contains(@"vnet.cn") || ls_urlreferhostname.ToLower().Contains(@"zhongsou") || ls_urlreferhostname.ToLower().Contains(@"iask"))
                                //            {
                                //                if (ls_urlrefer.ToLower().Contains("baidu") && (ls_urlrefer.ToLower().Contains("tn=utf7_dg") || ls_urlrefer.ToLower().Contains("pn=20&f=3") || ls_urlrefer.ToLower().Contains("tn=kzxf_pg")))
                                //                {
                                //                    ls_urlreferdecode = System.Web.HttpUtility.UrlDecode(ls_urlrefer, System.Text.Encoding.GetEncoding("utf-8"));
                                //                }
                                //                else
                                //                {
                                //                    ls_urlreferdecode = System.Web.HttpUtility.UrlDecode(ls_urlrefer, System.Text.Encoding.GetEncoding("gb2312"));
                                //                }
                                //            }
                                //            else
                                //            {
                                //                ls_urlreferdecode = System.Web.HttpUtility.UrlDecode(ls_urlrefer, System.Text.Encoding.GetEncoding("utf-8"));
                                //            }

                                //            //ls_urlreferdecode = System.Web.HttpUtility.UrlDecode(ls_urlrefer, System.Text.Encoding.GetEncoding("gb2312"));
                                //        }
                                //    }
                                //    else
                                //    {
                                //        ls_urlreferdecode = System.Web.HttpUtility.UrlDecode(ls_urlrefer, System.Text.Encoding.GetEncoding("utf-8"));
                                //    }


                                //    //if (ls_urlrefer.ToLower().Contains("google") || ls_urlreferhostname.Contains("bing") || ls_urlreferhostname.Contains("yahoo") || ls_urlreferhostname.Contains("dmoz") || ls_urlreferhostname.Contains(@"people258.com/Search/SearchResult.aspx"))
                                //    //{
                                //    //    ls_urlreferdecode = System.Web.HttpUtility.UrlDecode(ls_urlrefer, System.Text.Encoding.GetEncoding("utf-8"));
                                //    //}
                                //    //else if (ls_urlrefer.ToLower().Contains("baidu") || ls_urlreferhostname.Contains("soso") || ls_urlreferhostname.Contains("youdao") || ls_urlreferhostname.Contains("sogou") || ls_urlreferhostname.Contains("gougou") || ls_urlreferhostname.Contains(@"welcome1.zj.vnet.cn"))
                                //    //{
                                //    //    if (ls_urlrefer.ToLower().Contains("baidu") && (ls_urlrefer.ToLower().Contains("tn=utf7_dg") || ls_urlrefer.ToLower().Contains("pn=20&f=3") || ls_urlrefer.ToLower().Contains("tn=kzxf_pg")))
                                //    //    {
                                //    //        ls_urlreferdecode = System.Web.HttpUtility.UrlDecode(ls_urlrefer, System.Text.Encoding.GetEncoding("utf-8"));
                                //    //    }
                                //    //    else
                                //    //    {
                                //    //        ls_urlreferdecode = System.Web.HttpUtility.UrlDecode(ls_urlrefer, System.Text.Encoding.GetEncoding("gb2312"));
                                //    //    }
                                //    //}
                                //    //else
                                //    //{
                                //    //    ls_urlreferdecode = System.Web.HttpUtility.UrlDecode(ls_urlrefer, System.Text.Encoding.GetEncoding("utf-8"));
                                //    //}

                                //}
                              
                              
                            }
                            if (ls_urlrefer.Length > 1600)
                            {
                                ls_urlrefer = ls_urlrefer.Substring(0, 1600);
                            }
                            sb.Append(",'" + ls_urlrefer + "'");
                            //if (ls_urlreferdecode.Length >1600)
                            //{
                            //    ls_urlreferdecode = GetLengthString(ls_urlreferdecode, 1600);
                            //    //ls_urlreferdecode = ls_urlreferdecode.Substring(0, 1600);
                            //}
                            sb.Append(",'" + ls_urlreferdecode + "'");
                            if (ls_urlreferhostname.Length > 100)
                            {
                                ls_urlreferhostname = ls_urlreferhostname.Substring(0, 100);
                            }
                            sb.Append(",'" + ls_urlreferhostname + "'");
                            string ls_browsercancombineformsindeck = objApp.Request.Browser.CanCombineFormsInDeck.ToString();
                            if (ls_browsercancombineformsindeck.Length > 5)
                            {
                                ls_browsercancombineformsindeck = ls_browsercancombineformsindeck.Substring(0, 5);
                            }
                            sb.Append(",'" + ls_browsercancombineformsindeck + "'");
                            string ls_browserismobiledevice = objApp.Request.Browser.IsMobileDevice.ToString();
                            if (ls_browserismobiledevice.Length > 5)
                            {
                                ls_browserismobiledevice = ls_browserismobiledevice.Substring(0, 5);
                            }
                            sb.Append(",'" + ls_browserismobiledevice+ "'");
                            string ls_browsermobiledevicemanufacturer = objApp.Request.Browser.MobileDeviceManufacturer;
                            if (ls_browsermobiledevicemanufacturer.Length > 30)
                            {
                                ls_browsermobiledevicemanufacturer = ls_browsermobiledevicemanufacturer.Substring(0, 30);
                            }
                            sb.Append(",'" + ls_browsermobiledevicemanufacturer + "'");
                            string ls_browsermobiledevicemodel = objApp.Request.Browser.MobileDeviceModel;
                            if (ls_browsermobiledevicemodel.Length > 30)
                            {
                                ls_browsermobiledevicemodel = ls_browsermobiledevicemodel.Substring(0, 30);
                            }
                            sb.Append(",'" + ls_browsermobiledevicemodel + "'");
                            sb.Append("," + objApp.Request.Browser.NumberOfSoftkeys );
                            string ls_contentencoding = objApp.Request.ContentEncoding.BodyName;
                            if (ls_contentencoding.Length > 10)
                            {
                                ls_contentencoding = ls_contentencoding.Substring(0, 10);
                            }

                            string ls_cookiesname = ls_website;
                            if (ls_cookiesname.Length == 0)
                            {
                                ls_cookiesname = "WebSiteVisit";
                            }

                            if (objApp.Request.Cookies.Get(ls_cookiesname) == null || (objApp.Request.Cookies.Get(ls_cookiesname).HasKeys == true && objApp.Request.Cookies.Get(ls_cookiesname).Values[ls_webcookiesname] == null))
                            {
                                HttpCookie cookie = new HttpCookie(ls_website);
                                Random r = new Random();
                                int li_i = r.Next(1000000, 100000000);
                                cookie.Values[ls_webcookiesname] = ls_webcookiesname + "_" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "_" + li_i.ToString();
                                cookie.Expires = DateTime.Now.AddDays(int.Parse(ls_webcookiesexpires));
                                objApp.Response.Cookies.Add(cookie);
                            }

                            if (objApp.Request.Cookies.Get(ls_cookiesname) != null && (objApp.Request.Cookies.Get(ls_cookiesname).HasKeys == true && objApp.Request.Cookies.Get(ls_cookiesname).Values[ls_webcookiesname] != null))
                            {
                                ls_webcookiesvalue =objApp.Server.HtmlEncode(objApp.Request.Cookies[ls_cookiesname][ls_webcookiesname].ToString());

                                if (ls_webcookiesvalue.Length > 80)
                                {
                                    ls_webcookiesvalue = ls_webcookiesvalue.Substring(0, 80);
                                }

                            }

                            sb.Append(",'" + ls_contentencoding + "'");
                            sb.Append("," + objApp.Request.Browser.ScreenBitDepth);
                            sb.Append(",'" + ls_website + "'");
                            sb.Append(",'" + ls_webcookiesvalue + "'");
                            sb.Append(",'" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'");
                            sb.Append(")");

                            cmd.CommandText = sb.ToString();
                            cmd.ExecuteNonQuery();

                            ////插入测试数据
                            //for (int i = 2; i < 5; i++)
                            //{
                            //    cmd.CommandText = string.Format("INSERT INTO [test](name) VALUES ('中文测试')");
                            //    cmd.ExecuteNonQuery();
                            //}

                            //for (int i = 5; i < 10; i++)
                            //{
                            //    cmd.CommandText = string.Format("INSERT INTO [test](name) VALUES ( 'English Test')");
                            //    cmd.ExecuteNonQuery();
                            //}
                            dbTrans.Commit();     //提交事务执行

                        }

                    }
                }
            }
            catch
            {

            }
        }
    }
}
